<?php

namespace app\shop\controller;

use think\Controller;
// 引入邮箱
use app\common\library\Email;

class Business extends Controller
{
    public function _initialize()
    {
        // 继承父类
        parent::_initialize();
        $this->BusinessModel = model('Business.Business');
        $this->SourceModel = model('Business.Source');
        $this->EmsModel = model('Ems');
        $this->RecordModel = model('Business.Record');
        $this->CommissionModel = model('Business.Commission');
        $this->OrderModel = model('Product.Order');
        $this->OrderProductModel = model('Product.OrderProduct');
        $this->ProductModel = model('Product.Product');
    }

    // 登陆
    public function login()
    {
        if ($this->request->isPost()) {
            $mobile = $this->request->param('mobile', '', 'trim');
            $password = $this->request->param('password', '', 'trim');
            $token = $this->request->param('token', null, 'trim');

            // 数据查询用户信息是否存在
            $Business = $this->BusinessModel->where('mobile', $mobile)->find();

            // 登陆
            if ($Business) {
                $password = md5($password . $Business['salt']);

                if ($password != $Business['password']) {
                    $this->error('密码错误');
                    exit;
                }

                // 删除不需要的信息
                unset($Business['password']);
                unset($Business['salt']);

                $this->success('登陆成功', '', $Business);
            }
            // 注册
            else {
                // 密码盐
                $salt = build_randstr();

                // 密码加密
                $password = md5($password . $salt);

                // 查询某个字段的值
                $sourceid = $this->SourceModel->where('name', 'like', '%云课堂%')->value('id');

                $data = [
                    'mobile' => $mobile,
                    'nickname' => $mobile,
                    'password' => $password,
                    'salt' => $salt,
                    'gender' => '0',
                    'sourceid' => $sourceid ?? null,
                    'auth' => '0'
                ];

                // 判断是否有推荐人
                if ($token) {
                    // 查询所有用户信息
                    $businesslist = $this->BusinessModel->select();
                    // 遍历所有用户信息
                    foreach ($businesslist as $item) {
                        // 加密用户ID和手机号
                        $business = md5($item['id'] . $item['mobile']);

                        // 判断是否与请求中token匹配(即推荐人)
                        if ($token == $business) {
                            $data['parentid'] = $item['id'];
                            break;
                        }
                    }
                }

                $result = $this->BusinessModel->validate('common/Business/Business')->save($data);

                if ($result === false) {
                    $this->error($this->BusinessModel->getError());
                    exit;
                } else {
                    // 通过自增ID获取刚注册的客户信息
                    $Business = $this->BusinessModel->find($this->BusinessModel->id);

                    // 删除不需要的信息
                    unset($Business['password']);
                    unset($Business['salt']);

                    $this->success('注册登录成功', '', $Business);
                    exit;
                }
            }
        }
    }

    // 校验
    public function check()
    {
        if ($this->request->isPost()) {
            $busid = $this->request->param('busid', 0, 'trim');
            $mobile = $this->request->param('mobile', '', 'trim');

            $Business = $this->BusinessModel->where(['id' => $busid, 'mobile' => $mobile])->find();

            if (!$Business) {
                $this->error('用户不存在');
                exit;
            }

            // 删除不需要的信息
            unset($Business['password']);
            unset($Business['salt']);

            $this->success('登陆成功', '', $Business);
        }
    }


    // 基本资料
    public function profile()
    {
        if ($this->request->isPost()) {
            $params = $this->request->param();
            $busid = $this->request->param('busid', 0, 'trim');

            $Business = $this->BusinessModel->find($busid);

            if (!$Business) {
                $this->error('用户不存在');
                exit;
            }

            $data = [
                'id' => $busid,
                'nickname' => $params['nickname'],
                'mobile' => $params['mobile'],
                'gender' => $params['gender'],
                'province' => $params['province'],
                'city' => $params['city'],
                'district' => $params['district']
            ];

            // 判断是否修改邮箱
            if (isset($params['email']) && $params['email'] != $Business['email']) {
                $data['email'] = $params['email'];
                $data['auth'] = '0';
            }

            // 判断是否修改密码
            if (isset($params['password']) && !empty($params['password'])) {
                // 密码盐
                $data['salt'] = build_randstr();

                // 密码加密
                $data['password'] = md5($params['password'] . $data['salt']);
            }


            // 判断是否修改头像
            if (isset($_FILES['avatar']) && $_FILES['avatar']['size'] > 0 && $_FILES['avatar']['error'] == 0) {

                $res = upload('avatar');

                if ($res == '') {
                    $this->error('头像上传失败');
                    exit;
                }

                $data['avatar'] = $res;
            }

            // 显式指定更新数据操作  需要验证场景
            $result = $this->BusinessModel->validate('common/Business/Business.edit')->isUpdate(true)->save($data);

            if ($result === false) {
                if (isset($_FILES['avatar']) && $_FILES['avatar']['size'] > 0 && $_FILES['avatar']['error'] == 0) {
                    is_file(trim($data['avatar'], '/')) && unlink(trim($data['avatar'], '/'));
                }
                $this->error($this->BusinessModel->getError());
                exit;
            } else {
                if (isset($_FILES['avatar']) && $_FILES['avatar']['size'] > 0 && $_FILES['avatar']['error'] == 0) {
                    is_file(trim($Business['avatar'], '/')) && unlink(trim($Business['avatar'], '/'));
                }
                $this->success('修改资料成功', 'home/business/index');
                exit;
            }
        }
    }

    // 发送邮件
    public function send()
    {
        if ($this->request->isPost()) {
            $busid = $this->request->param('busid', 0, 'trim');

            $Business = $this->BusinessModel->find($busid);

            if (!$Business) {
                $this->error('用户不存在');
                exit;
            }


            $emsinfo = $this->EmsModel->where('email', $Business['email'])->find();

            if ($emsinfo) {
                $this->success('邮件已发送，请注意查收');
                exit;
            }

            // 启动事务
            $this->EmsModel->startTrans();

            // 获取验证码
            $code = build_randstr(4);

            $EmsData = [
                'event' => 'VUE商城邮箱认证',
                'email' => $Business['email'],
                'code' => $code
            ];

            $EmsStatus = $this->EmsModel->save($EmsData);

            if ($EmsStatus === false) {
                $this->error($this->EmsModel->getError());
                exit;
            }

            // 实例化一个Email对象
            $email = new Email;

            $content = "<h1>VUE商城邮箱验证码: $code</h1>";

            $SendEms = $email->subject('VUE商城邮箱认证')->to($Business['email'])->message($content)->send();

            if ($SendEms === false) {
                // 回滚事务
                $this->EmsModel->rollback();
                $this->error($email->getError());
                exit;
            }

            if ($EmsStatus === false || $SendEms === false) {
                $this->EmsModel->rollback();
                $this->error('发送邮件失败');
                exit;
            } else {
                // 提交事务
                $this->EmsModel->commit();
                $this->success('发送邮件成功');
                exit;
            }
        }
    }

    // 邮箱认证
    public function email()
    {
        if ($this->request->isPost()) {
            $busid = $this->request->param('busid', 0, 'trim');
            $code = $this->request->param('code', '', 'trim');

            $Business = $this->BusinessModel->find($busid);

            if (!$Business) {
                $this->error('用户不存在');
                exit;
            }

            $emsinfo = $this->EmsModel->where(['email' => $Business['email'], 'code' => $code])->find();

            if (!$emsinfo) {
                $this->error('验证码错误，请重新输入');
                exit;
            }

            // 启动事务
            $this->EmsModel->startTrans();
            $this->BusinessModel->startTrans();

            $EmsStatus = $this->EmsModel->destroy($emsinfo['id']);

            if ($EmsStatus === false) {
                $this->error($this->EmsModel->getError());
                exit;
            }

            $BusinessStatus = $this->BusinessModel->where('id', $busid)->update(['auth' => '1']);

            if ($BusinessStatus === false) {
                $this->EmsModel->rollback();
                $this->error($this->BusinessModel->getError());
                exit;
            }

            if ($EmsStatus === false || $BusinessStatus === false) {
                $this->EmsModel->rollback();
                $this->BusinessModel->rollback();
                $this->error('邮箱认证失败');
                exit;
            } else {
                $this->EmsModel->commit();
                $this->BusinessModel->commit();
                $this->success('邮箱认证成功');
                exit;
            }
        }
    }

    // 消费订单列表
    public function record()
    {
        if ($this->request->isPost()) {
            // 获取用户id
            $busid = $this->request->param('busid', 0, 'trim');

            // 组装查询条件
            $where = [
                'busid' => $busid,
            ];

            // 查询团队成员列表
            $list = $this->RecordModel->where($where)->order('id desc')->select();

            // 总数
            $count = $this->RecordModel->where($where)->count();

            if ($list) {
                $data = [
                    'count' => $count,
                    'list' => $list
                ];

                $this->success('', '', $data);
            } else {
                $this->error('暂无更多数据');
            }
        }
    }

    // 团队成员列表
    public function retailmember()
    {
        if ($this->request->isPost()) {
            // 获取用户id
            $busid = $this->request->param('busid', 0, 'trim');

            $Business = $this->BusinessModel->find($busid);

            if (!$Business) {
                $this->error('用户不存在');
                exit;
            }

            // 组装查询条件
            $where = [
                'parentid' => $Business['id']
            ];

            // 查询团队成员列表
            $list = $this->BusinessModel->where($where)->order('id desc')->select();

            // 总数
            $count = $this->BusinessModel->where($where)->count();

            if ($list) {
                $data = [
                    'count' => $count,
                    'list' => $list
                ];

                $this->success('', '', $data);
            } else {
                $this->error('暂无更多数据');
            }
        }
    }

    // 提现列表
    public function commission()
    {
        if ($this->request->isPost()) {
            // 获取用户id
            $busid = $this->request->param('busid', 0, 'trim');
            $Business = $this->BusinessModel->find($busid);

            $where = [
                'commission.parentid' => $Business['id'],
                'commission.type' => 'product'
            ];

            $where['commission.status'] = '0';
            // 查询待提现列表
            $list = $this->CommissionModel->with(['business', 'orderProduct'])->where($where)->order('commission.createtime desc')->select();
            // 总数
            $count = $this->CommissionModel->with(['business', 'orderProduct'])->where($where)->count();

            // 查询已提现列表
            $where['commission.status'] = '1';
            $list2 = $this->CommissionModel->with(['business', 'orderProduct'])->where($where)->order('commission.createtime desc')->select();

            $cash = 0;
            if ($list2) {
                foreach ($list2 as $item) {
                    $cash += $item['amount'];
                }
            }
            $data = [
                'cash' => number_format($cash, 2, '.', ''),
            ];

            if ($list) {
                $sum = 0;
                foreach ($list as $item) {
                    $sum += $item['amount'];
                    $orderId = isset($item['orderProduct']['id']) ? $item['orderProduct']['id'] : 0;
                    $orderProduct = $this->OrderProductModel->where('orderid', $orderId)
                        ->with(['product'])
                        ->find();

                    $item['product'] = $orderProduct['product'];
                }

                $data = [
                    'count' => $count,
                    'list' => $list,
                    'sum' => number_format($sum, 2, '.', ''),
                    'cash' => number_format($cash, 2, '.', '')
                ];

                $this->success('', '', $data);
            } else {
                $this->success('暂无更多数据', '', $data);
            }
        }
    }

    // 提现
    public function getMoney()
    {
        $busid = $this->request->param('busid', 0, 'trim');
        // 获取用户信息
        $business = $this->BusinessModel->find($busid);

        $where = [
            'parentid' => $busid,
            'status' => '0',
        ];

        $commission = $this->CommissionModel->where($where)->select();

        if (!$commission) {
            $this->error('暂无提现记录');
            exit;
        }

        /*
            佣金记录表： 状态更新
            用户表： 余额更新
            消费记录表： 新增
        */
        $this->CommissionModel->startTrans();
        $this->BusinessModel->startTrans();
        $this->RecordModel->startTrans();

        $sum = 0;
        foreach ($commission as $item) {
            $CommissionStatus = $this->CommissionModel->where(['id' => $item['id']])->update(['status' => '1']);
            $sum += $item->amount;

            if ($CommissionStatus === false) {
                $this->error($this->CommissionModel->getError());
                exit;
            }
        }

        // 剩余余额
        $money = bcadd($business['money'], $sum, 2);

        $BusinessData = [
            'id' => $busid,
            'money' => $money
        ];

        $validate = [
            [
                'money' => ['number', 'egt:0'],
            ],
            [
                'money.number'  => '余额必须是数字类型',
                'money.egt'      => '余额不足请先充值',
            ]
        ];

        $BusinessStatus = $this->BusinessModel->validate(...$validate)->isUpdate(true)->save($BusinessData);

        if ($BusinessStatus === false) {
            $this->CommissionModel->rollback();
            $this->error($this->BusinessModel->getError());
            exit;
        }

        $RecordData = [
            'total' => $sum,
            'busid' => $busid,
            'content' => "提现佣金，￥{$sum}元"
        ];

        $RecordStatus = $this->RecordModel->validate('common/Business/Record')->save($RecordData);
        if ($RecordStatus === false) {
            $this->CommissionModel->rollback();
            $this->BusinessModel->rollback();
            $this->error($this->RecordModel->getError());
            exit;
        }

        if ($CommissionStatus === false || $BusinessStatus === false || $RecordStatus === false) {
            $this->CommissionModel->rollback();
            $this->BusinessModel->rollback();
            $this->RecordModel->rollback();
            $this->error('提现失败');
            exit;
        } else {
            $this->CommissionModel->commit();
            $this->BusinessModel->commit();
            $this->RecordModel->commit();
            $this->success('提现成功');
            exit;
        }
    }
}
